<?php
/**
 * Created by PhpStorm.
 * User: KaBuDa
 * Date: 2020/10/8
 * Time: 15:55
 */

namespace app\api\controller;


use app\common\controller\Api;
use fast\Http;
use think\Config;

class Pay extends Api
{
  protected $noNeedLogin='*';
    public function we()
    {

        $params = [
        'mch_appid' => Config::get('wechat.appid'),
        'mchid' => Config::get('wechat.mchid'),
        'nonce_str' => time(),
        'partner_trade_no' => '1298016501' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000),//商户订单号
        'openid' => 'oqoRL5yKA8RtxzhjBX-GIDIA7DEA',
        'check_name' => 'NO_CHECK',//是否验证用户真实姓名，这里不验证
        'amount' => 1,//付款金额，单位为分
//        $desc = "###提现",
        'desc' => 'ss',//描述信息
        'spbill_create_ip' => $this->request->ip()//获取服务器的ip

        ];
halt($this->unifiedOrder($params));
        return  $this->unifiedOrder($params);
    }

    public function getSign($arr)
    {
        //去除空值
        $arr= array_filter($arr);
        if(isset($arr['sign'])){
            unset($arr['sign']);
        }
        //按照
        ksort($arr);
        $str= $this->arrToUrl($arr).'&key='.Config::get('wechat.key');
        return strtoupper(md5($str));
    }

    protected function arrToUrl($arr)
    {
        return urldecode(http_build_query($arr));
    }

    protected function setSign($arr)
    {
        $arr['sign']=$this->getSign($arr);
        return $arr;
    }

    protected function checkSign($arr)
    {
        $sign=$this->getSign($arr);
        if($sign==$arr['sign']){
            return true;
        }else{
            return false;
        }
    }

    public function unifiedOrder($params)
    {

        $arr=  $this->setSign($params);

        $xmldata=$this->ArrToXml($arr);

        $data=Http::post('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers',$xmldata);

        $array= $this->XmlToArr($data);

        return $array;
    }

    public  function ArrToXml($arr)
    {
        if(!is_array($arr) || count($arr) == 0) return '';

        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    public function XmlToArr($xml)
    {
        if($xml == '') return '';
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }
}